<template>
  <div>
    <a-modal
      :title="patientDialogTitle"
      :visible="addPatientInfoVisible"
      :confirm-loading="confirmLoading"
      :footer="null"
      @cancel="handleCancel1"
      width="700px"
    >
      <a-form-model :labelCol="{ span: 8 }" :model="addParams" :wrapperCol="{ span: 16 }" ref="editform" :rules="rules">
        <a-row :gutter="[8, 8]">
          <a-col :span="10">
            <a-form-model-item label="姓名" ref="name" prop="patientName">
              <a-input
                v-model="addParams.patientName"
                :max-length="10"
                @blur="
                  () => {
                    $refs.name.onFieldBlur()
                  }
                "
                placeholder="请输入患者姓名"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="手机号码" required prop="patientMobile">
              <a-input v-model="addParams.patientMobile" placeholder="手机号码必须为纯11位数字" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="10">
            <a-form-model-item label="性别" prop="patientSex">
              <a-select v-model="addParams.patientSex" placeholder="性别">
                <a-select-option :value="1">男性</a-select-option>
                <a-select-option :value="2">女性</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="出生日期" prop="patientBirth">
              <a-date-picker
                v-model="addParams.patientBirth"
                :style="{ width: '215px' }"
                :disabled-date="disabledDate1"
                placeholder="请选择时间"
                @change="onChange1"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="10">
            <a-form-model-item label="身高" prop="height">
              <a-input-number v-model="addParams.height" placeholder="单位:cm" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="体重">
              <a-input-number v-model="addParams.weight" placeholder="单位:公斤" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!--<a-row :gutter='[8, 8]'>
          <a-col :span='10'>
            <a-form-model-item label='职业'>
              <a-select
                v-model='addParams.occupation'
                v-decorator="[
                  'LaborIntensity',
                  {
                    rules: [{ required: true, message: '职业' }],
                  },
                ]"
                placeholder='体力劳动'
              >
                <a-select-option :value='1'>轻体力劳动</a-select-option>
                <a-select-option :value='2'>中体力劳动</a-select-option>
                <a-select-option :value='3'>重体力劳动</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span='12'>
            <a-form-model-item label='医疗费别'>
              <a-select
                v-model='addParams.payMode'
                v-decorator="[
                  'payMode',
                  {
                    rules: [{ required: true, message: '医疗费别' }],
                  },
                ]"
                placeholder='医疗费别'
              >
                <a-select-option :value='1'>社会医疗基本保险</a-select-option>
                <a-select-option :value='2'>新型农村合作医疗保险</a-select-option>
                <a-select-option :value='3'>城镇居民医疗保险</a-select-option>
                <a-select-option :value='4'>商业保险</a-select-option>
                <a-select-option :value='5'>公费医疗</a-select-option>
                <a-select-option :value='6'>自费医疗</a-select-option>
                <a-select-option :value='7'>其它</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>-->
        <a-row :gutter="[8, 8]">
          <a-col :span="12"></a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="12"></a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="12" align="right">
            <a-button type="primary" @click="handleOk1">
              确定
            </a-button>
          </a-col>
          <a-col :span="12">
            <a-button type="default" @click="handleCancel1">
              取消
            </a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    
    <a-modal
      title="绑定医生"
      :visible="bindDoctorModalVisible"
      :confirm-loading="confirmLoading"
      :footer="null"
      @cancel="() => { bindDoctorModalVisible =false }"
      width="700px"
    >
      <a-form-model :labelCol="{ span: 8 }" :model="addParams" :wrapperCol="{ span: 16 }" ref="editform" :rules="rules">
        
        <a-row :gutter="[8, 8]">
          <a-col :span="10">
            <a-form-model-item label="机构">
              <j-select-depart
                style="width: 100%"
                v-model="orgCode"
                :trigger-change="true"
                customReturnField="orgCode"
                :multi="false"
              ></j-select-depart>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="选择成员">
              <a-select
                placeholder="请选择成员"
                style="width: 100%"
                :allowClear="true"
                v-model="bindDoctorId"
              >
                <a-select-option v-for="item in flupDoctorsList" :value="item.dataId" :key="item.doctorId"
                  >{{ item.doctorsName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="[8, 8]">
          <a-col :span="12"></a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="12"></a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="12" align="right">
            <a-button type="primary" @click="bindDoctorPaitent">
              确定
            </a-button>
          </a-col>
          <a-col :span="12">
            <a-button type="default" @click="() => { bindDoctorModalVisible = false }">
              取消
            </a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>

    <div class="it_search">
      <a-form-model :form="searchform" layout="inline" :rules="validatorRules">
        <a-form-model-item label="姓名">
          <a-input v-model="patientParams.patientName" placeholder="输入患者姓名" />
        </a-form-model-item>
        <a-form-model-item label="手机号">
          <a-input v-model="patientParams.patientMobile" placeholder="输入患者手机号" />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="searchPatient">
            查询
          </a-button>
          <a-button type="primary" @click="resetSearch">
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <a-card :bordered="false" class="card-area">
      <a-table
        :pagination="ipagination"
        :loading="loading"
        rowKey="dataId"
        :columns="patientColumns"
        :data-source="patients"
        @change="handleTableChange"
      >
        <div slot="gender" slot-scope="text">
          <span v-if="text == 1">男</span>
          <span v-else-if="text == 2">女</span>
          <span v-else>未知</span>
        </div>
        <template slot="age" slot-scope="text, record">
          <span v-if="record.age != null && record.age != 0">{{text}}岁</span>
          <span v-else>未知</span>
        </template>
        <a slot="action" slot-scope="text, record">
          <a @click="handleAddPatient(record)">编辑</a>
          <a-divider type="vertical"/>
          <a :disabled="record.doctorName != null" type="primary" @click="handleBindDoctor(record)">绑定医生</a>
        </a>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { PAGE_MENU_TYPE } from '@/store/mutation-types'
import { getAction, postAction, deleteAction } from '@/api/manage'
import moment from 'moment'

const patientColumns = [
  {
    title: '姓名',
    dataIndex: 'patientsName',
    width: 100
  },
  {
    title: '手机号',
    dataIndex: 'patientsMobile',
    width: 120
  },
  {
    title: '性别',
    dataIndex: 'patientsSex',
    width: 120,
    scopedSlots: { customRender: 'gender' }
  },
  {
    title: '年龄',
    dataIndex: 'age',
    width: 120,
    scopedSlots: { customRender: 'age' }
  },
  {
    title: '所属医生',
    dataIndex: 'doctorName',
    width: 200,
    align: 'center'
  },
  {
    title: '操作',
    key: 'operation',
    width: 400,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  data() {
    return {
      loading: true,
      tags: [],
      selectedTags: [],
      checked1: true,
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 20,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      orgCode: '',
      patientQueryUrl: '/patient/all',
      addPatientUrl: '/100/12/1001203',
      patientParams: {
        pageNum: 1,
        pageSize: 20,
        patientName: '',
        patientMobile: ''
      },
      validatorRules: {
        patientMobile1: [{ validator: this.isRightMobile }]
      },
      patientColumns,
      patients: [],
      selectedRowKeys: [],
      visible: false,
      tempName: '',
      ifProhibit: false,
      showWordLimit: false,
      batchIds: [],
      batchChangePatientGroupVisible: false,
      confirmLoading: false,
      groupId: 0,
      addPatientInfoVisible: false,
      patientDialogTitle: '新增患者信息',
      isEditPatient: false,
      form: this.$form.createForm(this),
      searchform: this.$form.createForm(this),
      addParams: {},
      deletePatientInfoVisible: false,
      activeGroupId: 0,
      rules: {
        patientName: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
        patientMobile: [
          { required: true, message: '请输入手机号码', trigger: 'change' },
          { validator: this.isRightMobileNumber, message: '手机号码格式不正确' }
        ],
        patientBirth: [{ required: true, message: '请选择时间' }],
        height: [{ required: true, message: '请填写身高' }],
        patientSex: [{ required: true, message: '请选择性别', trigger: 'change' }]
      },
      bindDoctorModalVisible: false,
      flupDoctorsList: [],
      bindDoctorId: null,
      currentPatientId: null
    }
  },
  watch: {
    orgCode: function(value) {
      if (value) {
        this.getFlupDoctorsList()
      }
    }
  },
  created() {
    this.orgCode = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.orgCode
    this.getPatients()
  },
  methods: {
    ...mapGetters(['doctorId']),
    handleBindDoctor(record) {
      this.currentPatientId = record.dataId
      this.bindDoctorModalVisible = true
    },

    getFlupDoctorsList() {
      postAction('/doctor/list', { orgCode: this.orgCode }).then(res => {
        if (res.success) {
          this.flupDoctorsList = res.result
          this.bindDoctorId = null
        }
      })
    },
    bindDoctorPaitent() {
      this.confirmLoading = true
      let data = {
        patientId: this.currentPatientId,
        doctorId: this.bindDoctorId
      }
      postAction('/patient/doctor/bind', data)
        .then(res => {
          if (res.success) {
            this.currentPatientId = null
            this.bindDoctorId = null
            this.$message.success('绑定成功')
            this.bindDoctorModalVisible = false
            this.getPatients()
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    getPatients() {
      this.loading = true
      this.patientParams.doctorId = this.doctorId()
      postAction(this.patientQueryUrl, this.patientParams)
        .then(res => {
          if (res.success) {
            this.patients = res.result.records
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange(pagination) {
      this.ipagination = pagination
      this.patientParams.pageNum = pagination.current
      this.patientParams.pageSize = pagination.pageSize
      this.getPatients()
    },
    handleSelect(item) {
      console.log(item)
    },
    /**
     * 新增患者
     */
    handleAddPatient(patient) {
      this.isEditPatient = patient && patient.dataId
      this.patientDialogTitle = this.isEditPatient ? '编辑患者信息' : '新增患者信息'
      if (this.isEditPatient) {
        this.addParams = {
          patientId: patient.dataId,
          patientName: patient.patientsName,
          patientMobile: patient.patientsMobile,
          patientSex: patient.patientsSex,
          patientBirth: patient.patientsBirthday,
          height: patient.patientsHeight,
          weight: patient.patientsWeight
        }
      } else {
        this.addParams = {}
      }
      this.addPatientInfoVisible = true
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.error('请选择患者')
      } else {
        this.deletePatientInfoVisible = true
      }
    },
    handleOk1(e) {
      this.confirmLoading = true
      //    setTimeout(() => {

      this.$refs.editform.validate(valid => {
        if (valid) {
          this.addParams.doctorId = this.doctorId()
          postAction(this.addPatientUrl, this.addParams).then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.addPatientInfoVisible = false
              this.getPatients()
              this.confirmLoading = false
            } else {
              this.$message.error(res.message)
            }
          })
          
        } else {
          console.log('error')
          return false
        }
      })

      //    }, 2000)
    },
    handleCancel1(e) {
      console.log('Clicked cancel button')
      this.$refs.editform.resetFields()
      this.addPatientInfoVisible = false
      //    this.addParams = {}
    },
    isRightMobile(rule, value, callback) {
      if (typeof this.patientParams.patientMobile === 'undefined' || this.patientParams.patientMobile === '') {
        callback()
      } else {
        const regex = /^1[3456789]\d{9}$/
        if (!regex.test(this.patientParams.patientMobile)) {
          callback(new Error('请输入正确手机格式'))
        } else {
          callback()
        }
      }
    },
    isRightMobileNumber(rule, value, callback) {
      if (typeof value === 'undefined' || value === '') {
        callback()
      } else {
        const regex = /^1[3456789]\d{9}$/
        if (!regex.test(value)) {
          callback(new Error('请输入正确手机格式'))
        }
        callback()
      }
    },

    isHeight(rule, value, callback) {
      if (typeof value === 'undefined' || value === '') {
        callback()
      } else {
        const regex = /^(\+)?\d+(\.\d+)?$/
        if (!regex.test(value)) {
          callback(new Error('请输入正确身高'))
        }
        callback()
      }
    },

    isWeight(rule, value, callback) {
      if (typeof value === 'undefined' || value === '') {
        callback()
      } else {
        const regex = /^(\+)?\d+(\.\d+)?$/
        if (!regex.test(value)) {
          callback(new Error('请输入正确体重'))
        }
        callback()
      }
    },

    disabledDate1(current) {
      return current > moment().endOf('day')
    },

    onChange1(date, dateString) {
      this.addParams.patientBirth = dateString + ' 00:00:00'
    },

    handleOk2(e) {
      this.confirmLoading = true
      setTimeout(() => {
        this.deletePatientInfoVisible = false

        postAction(this.deletePatientUrl, {
          patientIds: this.selectedRowKeys
        }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })

        this.getPatientGroups()
        this.confirmLoading = false
      }, 2000)
    },
    handleCancel2(e) {
      console.log('Clicked cancel button')
      this.deletePatientInfoVisible = false
    },

    handleOk3(e) {
      this.confirmLoading = true
      setTimeout(() => {
        this.batchChangePatientGroupVisible = false

        postAction(this.changeGroupIdUrl, {
          doctorId: this.doctorId(),
          groupId: this.groupId,
          patientIds: this.selectedRowKeys
        }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })

        this.getPatientGroups()
        this.confirmLoading = false
        this.groupId = 0
      }, 2000)
    },
    handleCancel3(e) {
      console.log('Clicked cancel button')
      this.batchChangePatientGroupVisible = false
      this.groupId = 0
    },

    handleChangeActiveGroupId(key) {
      if (key === 'addBtn') {
        return false
      } else {
        this.activeGroupId = key
      }
    },
    handleAddGroup() {
      this.$refs.groupModalForm.add()
      this.$refs.groupModalForm.title = '新增分组'
      this.$refs.groupModalForm.disableSubmit = false
    },
    handleEditGroup(record) {
      this.$refs.groupModalForm.edit(record)
      this.$refs.groupModalForm.title = '编辑分组'
      this.$refs.groupModalForm.disableSubmit = false
    },
    groupModalFormOk() {
      this.getPatientGroups()
    },
    handleDeleteGroup(id) {
      deleteAction('group/remove', { id, doctorId: this.doctorId() }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getPatientGroups()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleChange(tag, checked) {
      const { selectedTags } = this
      const nextSelectedTags = checked ? [...selectedTags, tag] : selectedTags.filter(t => t !== tag)
      console.log('You are interested in: ', nextSelectedTags)
      this.selectedTags = nextSelectedTags
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.patientParams.tagIds = nextSelectedTags.toString()
      this.getPatients()
    },
    searchPatient() {
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.getPatients()
    },
    resetSearch() {
      this.patientParams.patientName = ''
      this.patientParams.patientMobile = ''
      this.patientParams.groupId = this.activeGroupId
      this.patientParams.pageNum = 1
      this.selectedTags = []
      this.patientParams.tagIds = ''
      this.searchform.resetFields()
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.getPatients()
    }
  }
}
</script>

<style lang="less" scoped>
.ant-btn {
  margin: 0.2rem;
}

.flup-item {
  margin: 1rem;
  padding: 0.5rem;
  display: flex;
  align-items: center;

  span {
    flex: 1;
  }
}

#tip {
  display: block;

  #warning {
    // margin: 0.3rem;
    text-align: right;
  }
}

.it_search {
  background: white;
  border-top-left-radius: 2px;
  border-top-right-radius: 2px;
  padding: 10px 20px;
  color: rgba(0, 0, 0, 0.85);
}

.it_search > div {
  margin-bottom: 10px;
}

.ant-tag {
  font-size: 14px;
  border: 1px solid rgba(0, 0, 0, 0.65);
  margin-bottom: 5px;
}

.ant-tag-checkable-checked {
  border: 1px solid #f5222d;
}
.ant-input-number {
  width: 100%;
}
</style>

